//
//  UIApplication+More.swift
//  ClockWidget
//
//  Created by TSYH on 2023/10/12.
//

import UIKit
import MessageUI
import AVFoundation

public extension UIApplication {
    static var keyWindow: UIWindow? {
        return UIApplication.shared.windows.first(where: { $0.isKeyWindow })
    }
    
    static var rootViewController: UIViewController? {
        return keyWindow?.rootViewController
    }
    
    static var topViewController: UIViewController? {
        return keyWindow?.rootViewController?.topController
    }
    
    // 打开Photo
    func openPhotoLibrary() {
        if let url = URL(string: "photos-redirect://"),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    func openSetting() {
        if let url = URL(string: UIApplication.openSettingsURLString),
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
    
    func openAppleMusic() {
        if let url = URL(string: "music://"),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
    
    func openSpotify() {
        if let url = URL(string: "spotify://"),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
    
    // 是否安装库乐队
    func garageBandInstalled() -> Bool {
        if let url = URL(string: "garageband://") {
            return UIApplication.shared.canOpenURL(url)
        }
        return false
    }
    
    /// 打开外部链接
    func openExternal(url: String) {
        if let url = URL(string: url),
           UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
}

public extension UIApplication {
    // 获取系统音量
    static func getSystemVolume() -> Float {
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(.playback) // 设置音频会话为播放模式
            return audioSession.outputVolume
        } catch {
            print("Failed to set audio session category.")
            return -1.0
        }
    }
}
